package com.ruicar.afs.cloud.afscase.dispatch.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoTempService;
import com.ruicar.afs.cloud.afscase.dispatch.DispatchContext;
import com.ruicar.afs.cloud.afscase.dispatch.annotation.Dispatch;
import com.ruicar.afs.cloud.afscase.dispatch.enums.DispatchTypeEnum;
import com.ruicar.afs.cloud.afscase.dispatch.service.DispatchBaseServcie;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.processor.service.LoanApproveWorkflowService;
import com.ruicar.afs.cloud.afscase.processor.vo.LoanBusinessDataVO;
import com.ruicar.afs.cloud.afscase.processor.vo.LoanWorkflowDataVO;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ApplyStatusEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStageEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import com.ruicar.afs.cloud.seats.entity.RegularValue;
import com.ruicar.afs.cloud.seats.service.RegularValueService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>Description: 启动放款审核流程</p>
 *
 * @author fangchenliang
 */
@Service
@AllArgsConstructor
@Dispatch(name = "启动放款审核流程", dependsOn = "dispatchTimeBeforeLoanService", group = DispatchTypeEnum.LOAN)
@Slf4j
public class DispatchStartLoanService extends DispatchBaseServcie {
    private RegularValueService valueService;
    private WorkProcessScheduleInfoTempService scheduleInfoTempService;
    private LoanApproveWorkflowService loanApproveWorkflowService;
    /**
     * MQ通知
     */
    private ApproveLoanInfoService approveLoanInfoService;

    @Override
    public void process(DispatchContext context) throws Exception {

        List list = (List) (Optional.ofNullable(context.get(LOAN_KEY)).orElse(new ArrayList()));
        if (list.isEmpty()) {
            return;
        }
        for (Object object : list) {
            CaseContractInfo contractInfo = (CaseContractInfo) object;
            JSONObject jsonObject = (JSONObject) context.get(contractInfo.getId());
            RuleRunResult result = RuleHelper.runRule(jsonObject, "loanProcedure", false, RuleRunEnum.SERIAL);
            if (result.getHit()) {
                List listNo = result.getResults().stream().map(s -> s.getRuleNo()).collect(Collectors.toList());
                if (listNo.isEmpty())
                    return;
                List<RegularValue> valueList = valueService.listByIds(listNo);
                if (valueList == null || valueList.isEmpty())
                    return;
                String[] value = valueList.stream().map(s -> {
                    String[] str = s.getValue().split("#");
                    return str;
                }).max(Comparator.comparing(s -> s[1])).get();

                log.info("流程匹配命中结果[{}],流程编号为[{}]", result.getHit(), value[1]);
                try{
                    if(StrUtil.equals(contractInfo.getBusinessStage(), BusinessStageEnum.WAIT_ASSIGN.getCode())) {
                        //异常解决
                        loanApproveWorkflowService.resumeFlow(contractInfo.getWorkExceptionId());
                    }else {
                        //流程分支条件参数
                        LoanBusinessDataVO loanBusinessDataVO = LoanBusinessDataVO.builder()
                                .assigned(WhetherEnum.NO.getCode())
                                .build();

                        //流程发起
                        loanApproveWorkflowService.start(LoanWorkflowDataVO.builder()
                                .loanBusinessDataVO(loanBusinessDataVO)
                                .workProcessScheduleInfoTemp(scheduleInfoTempService.createWorkProcessor(contractInfo, value[1]))
                                .build());
                    }
                }catch (Exception e){
                    log.error("{}流程发起异常",contractInfo.getContractNo(),e);
                }
            }
        }
    }
}
